/**
 * Module dependencies.
 * 配置中间件，注册路由，启动服务器。
 */
const moduleAlias = require("module-alias");
moduleAlias.addAlias("@", __dirname + "/src"); // 添加别名

var app = require("@/main.js");

/**
 * Get port from environment and store in Express.
 */
const { APP_PORT } = require("@/config/config.default.js");
var port = normalizePort(APP_PORT || "3000");


/**
 * Create HTTP server.
 */

/**
 * Listen on provided port, on all network interfaces.
 */

app.listen(port, () => {
  console.log(`server is running on http://localhost:${APP_PORT || "3000"}`);
});
app.on("error", onError);
app.on("listening", onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error, ctx) {
  try {
    if (error.syscall !== "listen") {
      throw error;
    }

    var bind = typeof port === "string" ? "Pipe " + port : "Port " + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
      case "EACCES":
        console.error(bind + " requires elevated privileges");
        process.exit(1);
        break;
      case "EADDRINUSE":
        console.error(bind + " is already in use");
        process.exit(1);
        break;
      default:
        throw error;
    }
  } catch (error) {
    console.error(error);
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
  debug("Listening on " + bind);
}

const { sequelize } = require('@/model');

(async () => {
  try {
    await sequelize.authenticate();
    if (process.env.NODE_ENV === 'development') {
      // 开发环境可选：模型自动同步
      await sequelize.sync({ alter: true });
    } else {
      // 生产环境：只允许 migration
    }
    // ... 启动你的服务 ...
  } catch (err) {
    console.error('数据库连接或迁移失败:', err);
    process.exit(1);
  }
})();